package com.situ.system.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class JDBCUtil {

	private static ResourceBundle rb = ResourceBundle.getBundle("com.situ.system.util.JDBC");
	private static String cLassName = rb.getString("driver");
	private static String url = rb.getString("url");
	private static String user = rb.getString("user");
	private static String password = rb.getString("pass");

	// 1- 加载驱动
	static {
		try {
			Class.forName(cLassName);
		} catch (Exception e) {
			e.getCause();
		}
	}

	// 2- 获得链接
	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, user, password);
	}

	public static void close(Connection conn, Statement st, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (st != null) {
				st.close();
				st = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void close(Connection conn, Statement st) {
		close(conn, st, null);
	}

	public static void main(String[] args) throws SQLException {
		// 加载驱动 + 获得链接
		Connection con = JDBCUtil.getConnection();
		System.out.println(con);
		JDBCUtil.close(con, null); // 关闭的是插入的
	}

	private JDBCUtil() {

	}

	public static int shuai(String sql, Object... obj) {
		Connection connection = null;
		PreparedStatement ps = null;
		try {
			connection = getConnection();
			ps = connection.prepareStatement(sql);
			for (int i = 0; i < obj.length; i++) {
				ps.setObject(i + 1, obj[i]);
			}
			return ps.executeUpdate(); // 更新成功的
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(connection, ps);
		}
		return -1;
	}
}
